package com.example.hrsystem.ui.attendance;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hrsystem.R;
import com.example.hrsystem.data.model.AttendanceRecord;
import com.example.hrsystem.data.source.AppDatabase;
import com.example.hrsystem.model.DailyAttendanceRecord;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 考勤详情Activity
 * 显示本月的打卡记录详情，包括正常打卡和异常打卡
 */
public class AttendanceDetailActivity extends AppCompatActivity {

    private static final String TAG = "AttendanceDetail";
    
    private RecyclerView attendanceRecyclerView;
    private AttendanceDetailAdapter attendanceAdapter;
    private List<DailyAttendanceRecord> attendanceRecordList;
    private AppDatabase database;
    private String currentEmployeeId;
    private DailyAttendanceViewModel dailyAttendanceViewModel;
    
    private TextView normalDaysTextView;
    private TextView abnormalDaysTextView;
    private TextView attendanceRateTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attendance_detail);
        
        // 启用返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("考勤详情");
        }
        
        // 初始化数据库和用户信息
        database = AppDatabase.getDatabase(getApplicationContext());
        SharedPreferences userPrefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        currentEmployeeId = userPrefs.getString("employee_id", "1001"); // 默认值仅用于开发测试
        
        // 初始化ViewModel
        dailyAttendanceViewModel = new ViewModelProvider(this).get(DailyAttendanceViewModel.class);
        
        // 初始化UI组件
        initViews();
        
        // 加载考勤数据
        loadAttendanceData();
    }

    /**
     * 初始化UI组件
     */
    private void initViews() {
        normalDaysTextView = findViewById(R.id.normal_days_text_view);
        abnormalDaysTextView = findViewById(R.id.abnormal_days_text_view);
        attendanceRateTextView = findViewById(R.id.attendance_rate_text_view);
        
        attendanceRecyclerView = findViewById(R.id.attendance_detail_recycler_view);
        attendanceRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        attendanceRecordList = new ArrayList<>();
        attendanceAdapter = new AttendanceDetailAdapter(attendanceRecordList);
        attendanceRecyclerView.setAdapter(attendanceAdapter);
    }

    /**
     * 加载考勤数据
     */
    private void loadAttendanceData() {
        // 计算本月第一天和最后一天
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date startDate = calendar.getTime();
        
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date endDate = calendar.getTime();
        
        // 使用ViewModel获取指定日期范围内的数据
        dailyAttendanceViewModel.getDailyAttendanceRecordsByDateRange(currentEmployeeId, startDate, endDate).observe(this, new Observer<List<DailyAttendanceRecord>>() {
            @Override
            public void onChanged(List<DailyAttendanceRecord> records) {
                if (records != null) {
                    // 统计正常和异常打卡天数
                    int normalDays = 0;
                    int abnormalDays = 0;
                    
                    // 收集所有打卡记录
                    List<DailyAttendanceRecord> filteredRecords = new ArrayList<>();
                    for (DailyAttendanceRecord record : records) {
                        // 添加所有记录到列表中
                        filteredRecords.add(record);
                        
                        // 统计完整打卡记录
                        if ("正常".equals(record.getStatus())) {
                            normalDays++;
                        } else if ("异常".equals(record.getStatus())) {
                            abnormalDays++;
                        }
                    }
                    
                    // 计算出勤率
                    int totalWorkingDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                    float attendanceRate = totalWorkingDays > 0 ? (float) normalDays / totalWorkingDays * 100 : 0;
                    
                    // 更新统计数据
                    normalDaysTextView.setText(String.valueOf(normalDays));
                    abnormalDaysTextView.setText(String.valueOf(abnormalDays));
                    attendanceRateTextView.setText(String.format(Locale.getDefault(), "%.1f%%", attendanceRate));
                    
                    // 更新列表数据
                    attendanceRecordList.clear();
                    attendanceRecordList.addAll(filteredRecords);
                    attendanceAdapter.notifyDataSetChanged();
                }
            }
        });
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}